/*
 * @Author: 肖思汗 
 * @Date: 2025-07-11 21:34:52 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-26 19:51:03
 */
import { Button, Input, Price } from '@nutui/nutui-react-taro'
import { View, Text } from '@tarojs/components'
import Taro, { useDidShow, useRouter, useShareAppMessage } from '@tarojs/taro'
import clsx from 'clsx'
import { isEmpty } from 'lodash'
import { toJS } from 'mobx'
import { observer } from "mobx-react-lite"
import { ReactNode, useEffect, useRef, useState } from 'react'
import MyEmpty from 'src/components/MyEmpty/MyEmpty'
import MyScrollView from 'src/components/MyScrollView/MyScrollView'
import PageLayer from 'src/components/PageLayer/PageLayer'
import MyPopup from 'src/components/MyPopup/MyPopup'
import utils from 'src/utils/utils'
import utilsStore from 'src/utils/utilsStore'
import { CouponItem } from 'types/type'
import confirmOrderStore from '../ConfirmOrder/ConfirmOrderStore'
import styles from './myCoupons.module.less'
import myCouponsStore from './MyCouponsStore'
import userStore from 'src/pages/User/userStore'
import userInfoApi from '../UserInfo/userInfoApi'
import MyCouponsApi from './MyCouponsApi'
import utilsApi from 'src/api/utilsApi'
import userInfoStore from '../UserInfo/userInfoStore'

interface Iprops {
    children?: ReactNode
}

// 优惠券
const MyCoupons = observer((props: Iprops) => {

    const transferToken = useRef("");


    // 转赠优惠券
    useShareAppMessage(async () => {
        await new Promise(resolve => setTimeout(resolve, 200));

        // 等待设置 转赠码
        while (transferToken.current === "") {
            await new Promise(resolve => setTimeout(resolve, 200));
        }

        const coupon_imgs = await utilsApi.queryPropertyByTitle("coupon_imgs").then((coupon_imgs) => {
            console.log("coupon_imgs", coupon_imgs);
            return coupon_imgs;
        });

        return {
            title: '送你一张优惠券',
            path: `/subPages/AcceptInvitation/AcceptInvitation?transferToken=${transferToken.current}&userCode=${userInfoStore.userCode}`,
            imageUrl: utils.ossSuffix(coupon_imgs, 512),
        };
    });

    const calculateDaysRemaining = (expireTime: string): number => {
        const today = new Date();
        const expireDate = new Date(expireTime.replace(/-/g, '/'));
        const difference = expireDate.getTime() - today.getTime();
        return difference / (1000 * 3600 * 24);
    }

    // 新增倒计时组件
    const CountdownTimer = ({ expireTime }: { expireTime: string }) => {
        const [timeLeft, setTimeLeft] = useState<{
            days: number,
            hours: number,
            minutes: number,
            seconds: number
        }>({ days: 0, hours: 0, minutes: 0, seconds: 0 });
        const [isExpired, setIsExpired] = useState(false);

        useEffect(() => {
            const updateTimer = () => {
                const now = new Date();
                const endDate = new Date(expireTime.replace(/-/g, '/'));
                const difference = endDate.getTime() - now.getTime();

                if (difference <= 0) {
                    setIsExpired(true);
                    return;
                }

                setTimeLeft({
                    days: Math.floor(difference / (1000 * 60 * 60 * 24)),
                    hours: Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
                    minutes: Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)),
                    seconds: Math.floor((difference % (1000 * 60)) / 1000)
                });
            };

            updateTimer(); // 立即执行一次
            const timer = setInterval(updateTimer, 1000); // 每秒更新

            return () => clearInterval(timer); // 组件卸载时清除定时器
        }, [expireTime]);

        // 只显示7天内过期的优惠券倒计时
        if (isExpired || timeLeft.days >= 7) {
            return null;
        }

        return (
            <View className={styles.expireTip}>
                {timeLeft.days}天{timeLeft.hours}时{timeLeft.minutes}分{timeLeft.seconds}秒后过期
            </View>
        );
    };

    useDidShow(() => {

        myCouponsStore.getNextCouponList(true);

        userStore.awaitLogined().then(() => {
            const { transferToken, userCode } = Taro.getCurrentInstance().router?.params || {};

            // 如果带有邀请码 就跳转到接受邀请页面
            if (userCode) {
                Taro.redirectTo({
                    url: `/subPages/AcceptInvitation/AcceptInvitation?userCode=${userCode}&transferToken=${transferToken}`,
                });
                return;
            }

            const preTransferToken = Taro.getStorageSync("preTransferToken");
            if (transferToken && transferToken !== preTransferToken) {
                Taro.setStorageSync("preTransferToken", transferToken);
                MyCouponsApi.transferInfo(transferToken).then(res => {
                    console.log("优惠券的转赠信息", res);
                    if (res.data.transferState === "待接收") {
                        myCouponsStore.receiveToken(transferToken);
                    } else {
                        Taro.showToast({
                            title: res.data.transferState,
                            icon: 'none',
                            // complete: () => {
                            //     // 重定向一个不带参数的地址
                            //     Taro.redirectTo({
                            //         url: '/subPages/MyCoupons/MyCoupons',
                            //     });
                            // }
                        });
                    }
                });
            }
        });
    });

    const router = useRouter();
    const [selectedCoupon, setSelectedCoupon] = useState<CouponItem | null>(null);
    const [couponCode, setCouponCode] = useState('');
    const [showConfirmDialog, setShowConfirmDialog] = useState(false);

    const isSelectMode = (router.params.selectMode === 'true');
    const list = toJS(myCouponsStore.list);

    // 领取优惠券
    const handleReceiveCoupon = () => {
        // 扫二维码
        Taro.scanCode({
            success: (res) => {
                console.log("扫码结果", res.result);
                myCouponsStore.receive(res.result);
            }
        })
    }

    return (
        <PageLayer
            title='优惠券'
            showBack
            className={styles.myCoupons}
            hasTabBar={false}
        >
            <View className={styles.couponInputContainer}>
                <Input
                    className={styles.couponInput}
                    placeholder='请输入优惠券码'
                    value={couponCode}
                    onChange={(v: string) => {
                        setCouponCode(v);
                    }}
                />
                <Button
                    className={styles.scanBtn}
                    onClick={handleReceiveCoupon}
                >
                    扫码
                </Button>
                <Button
                    className={styles.receiveBtn}
                    onClick={() => {
                        if (couponCode) {
                            setCouponCode('');
                            myCouponsStore.receive(couponCode);
                        } else {
                            Taro.showToast({
                                title: '请输入优惠券码',
                                icon: 'none',
                                duration: 2000,
                            });
                        }
                    }}
                >
                    领取
                </Button>
            </View>

            <View className={styles.tabs}>
                {['未使用', '已使用', '已过期'].map((tab, index) => (
                    <View
                        key={index}
                        className={`${styles.tabItem} ${myCouponsStore.state === tab ? styles.active : ''}`}
                        onClick={() => {
                            myCouponsStore.setState(tab as '未使用' | '已使用' | '已过期');
                        }}
                    >
                        {tab}
                    </View>
                ))}
            </View>

            {
                isEmpty(list) &&
                <MyEmpty
                    style={{
                        marginTop: "16vh"
                    }}
                    description={`暂无${myCouponsStore.state}的优惠券`}
                />
            }

            {
                !isEmpty(list) &&
                <MyScrollView
                    style={{
                        height: utilsStore.containerHeight - (isSelectMode ? utils.rpx2px(200) : utils.rpx2px(80))
                    }}
                    onScrollBottom={() => {
                        myCouponsStore.getNextCouponList();
                    }}
                >
                    {
                        list.map(coupon => {
                            return (
                                <View
                                    key={coupon.couponCreateRecordId}
                                    className={clsx(
                                        styles.couponItem,
                                        (isSelectMode ? styles.selectable : ''),
                                        (selectedCoupon?.couponGetRecordId === coupon.couponGetRecordId && styles.selected)
                                    )}
                                    onClick={() => {
                                        if (
                                            isSelectMode &&
                                            myCouponsStore.orderPrice >= coupon.usePrice &&
                                            coupon.transferState !== "待接收" &&
                                            coupon.state === "未使用" &&
                                            calculateDaysRemaining(coupon.expireTime) > 0
                                        ) {
                                            setSelectedCoupon(coupon)
                                        }
                                    }}
                                >
                                    {
                                        coupon.state === "未使用" &&
                                        calculateDaysRemaining(coupon.expireTime) < 7 &&
                                        calculateDaysRemaining(coupon.expireTime) >= 0 && (
                                            <View className={styles.nearExpireTag}>快过期</View>
                                        )}
                                    <View className={styles.mainContent}>
                                        <View className={styles.leftPart}>
                                            <View className={styles.amount}>
                                                <Price
                                                    price={coupon.couponPrice}
                                                    size="normal"
                                                    digits={1}
                                                    thousands
                                                />
                                            </View>
                                            <View className={styles.condition}>
                                                {(isSelectMode && myCouponsStore.orderPrice < coupon.usePrice) ? '未满' : '满'}
                                                &nbsp;&nbsp;
                                                <Price
                                                    price={coupon.usePrice}
                                                    size="normal"
                                                    digits={1}
                                                    thousands
                                                />
                                                &nbsp;&nbsp;
                                                {(isSelectMode && myCouponsStore.orderPrice < coupon.usePrice) ? '元不可用' : '元可用'}
                                            </View>
                                            <View className={styles.name}>{coupon.couponName}</View>
                                        </View>
                                        <View className={styles.rightPart}>

                                            {
                                                coupon.transferState === "待接收" &&
                                                <>
                                                    <Button
                                                        disabled
                                                    >
                                                        转赠中
                                                    </Button>
                                                    <Button
                                                        type='primary'
                                                        style={{
                                                            marginTop: "20px"
                                                        }}
                                                        onClick={() => {
                                                            myCouponsStore.cancelTransfer(coupon.couponGetRecordId);
                                                        }}
                                                    >
                                                        取消转赠
                                                    </Button>
                                                </>
                                            }

                                            {
                                                !isSelectMode &&
                                                coupon.transferState !== "待接收" &&
                                                coupon.state === "未使用" &&
                                                calculateDaysRemaining(coupon.expireTime) > 0 &&
                                                <>
                                                    <Button
                                                        type='primary'
                                                        onClick={() => {
                                                            Taro.switchTab({
                                                                url: '/pages/Category/Category'
                                                            });
                                                        }}
                                                    >
                                                        立即使用
                                                    </Button>
                                                    <Button
                                                        openType="share"
                                                        type='primary'
                                                        style={{
                                                            marginTop: "20px"
                                                        }}
                                                        onClick={() => {
                                                            transferToken.current = "";
                                                            MyCouponsApi.createToken(coupon.couponGetRecordId).then(res => {
                                                                transferToken.current = res.data.transferToken;
                                                            });
                                                        }}
                                                    >
                                                        转赠
                                                    </Button>
                                                </>
                                            }

                                            {
                                                calculateDaysRemaining(coupon.expireTime) > 0 &&
                                                coupon.state === "已使用" &&
                                                <View className={styles.status}>
                                                    {coupon.state}
                                                </View>
                                            }

                                            {
                                                calculateDaysRemaining(coupon.expireTime) <= 0 &&
                                                <Button
                                                    type='primary'
                                                    onClick={() => {
                                                        Taro.showModal({
                                                            title: '确认删除',
                                                            content: '确定要删除这张优惠券吗？',
                                                            success: (res) => {
                                                                if (res.confirm) {
                                                                    myCouponsStore.del(coupon.couponGetRecordId);
                                                                }
                                                            }
                                                        });
                                                    }}
                                                >
                                                    删除
                                                </Button>
                                            }

                                        </View>
                                    </View>
                                    <View className={clsx(styles.bottomInfo, calculateDaysRemaining(coupon.expireTime) < 7 ? styles.nearExpire : '')}>
                                        {
                                            (
                                                coupon.state === "未使用" &&
                                                calculateDaysRemaining(coupon.expireTime) < 7 &&
                                                calculateDaysRemaining(coupon.expireTime) >= 0
                                            ) ?
                                                <CountdownTimer expireTime={coupon.expireTime} />
                                                :
                                                <Text>有效期：{coupon.expireTime}</Text>
                                        }
                                    </View>
                                </View>
                            )
                        })
                    }
                </MyScrollView>
            }

            {
                isSelectMode &&
                <View className={styles.footer}>
                    <Button
                        type="primary"
                        className={styles.confirmBtn}
                        disabled={!selectedCoupon}
                        onClick={() => {
                            if (selectedCoupon) {
                                setShowConfirmDialog(true);
                            }
                        }}
                    >
                        确认选择
                    </Button>
                </View>
            }

            {/* 优惠券确认对话框 */}
            <MyPopup
                open={showConfirmDialog}
                hasMark={true}
                hasHeader={false}
                onClose={() => setShowConfirmDialog(false)}
                className={styles.centerPopup}
                style={{ padding: 0 }}
            >
                <View className={styles.confirmDialog}>
                    <Text className={styles.confirmDialogTitle}>确认使用优惠券</Text>
                    <Text className={styles.confirmDialogContent}>
                        {selectedCoupon?.couponName}
                    </Text>
                    <View className={styles.confirmDialogButtons}>
                        <Button
                            className={styles.cancelButton}
                            onClick={() => setShowConfirmDialog(false)}
                        >
                            取消
                        </Button>
                        <Button
                            type="primary"
                            className={styles.confirmButton}
                            onClick={() => {
                                if (selectedCoupon) {
                                    const pages = Taro.getCurrentPages()
                                    const prevPage = pages[pages.length - 2]
                                    if (prevPage) {
                                        prevPage.setData({
                                            selectedCoupon
                                        })
                                    }
                                    Taro.navigateBack();
                                    confirmOrderStore.setCoupon(selectedCoupon);
                                    setShowConfirmDialog(false);
                                }
                            }}
                        >
                            确定
                        </Button>
                    </View>
                </View>
            </MyPopup>
        </PageLayer>
    )
});

export default MyCoupons;